/**
 *  *2010-7-17 上午11:10:33  add 
 */
package com.base.myproject.client.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.swfupload.client.File;
import org.swfupload.client.SWFUpload;
import org.swfupload.client.SWFUpload.ButtonAction;
import org.swfupload.client.UploadBuilder;
import org.swfupload.client.event.DialogStartHandler;
import org.swfupload.client.event.FileDialogCompleteHandler;
import org.swfupload.client.event.FileQueueErrorHandler;
import org.swfupload.client.event.FileQueuedHandler;
import org.swfupload.client.event.SWFUploadLoadedHandler;
import org.swfupload.client.event.UploadCompleteHandler;
import org.swfupload.client.event.UploadErrorHandler;
import org.swfupload.client.event.UploadProgressHandler;
import org.swfupload.client.event.UploadStartHandler;
import org.swfupload.client.event.UploadSuccessHandler;

import com.base.myproject.client.system.Env;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * @author Administrator 2010-7-17 javazgw@gmail.com
 */
public class SWFFileUpload {

	// static SWFFileUpload swffileupload;
	Dialog d = new Dialog();
	private List<File> files = new ArrayList<File>();

	final HTML html = new HTML("");
	SWFUpload upload;
	UploadBuilder builder = new UploadBuilder();
	Button uploadbutton = new Button("上传");

	String params = "";

	public SWFFileUpload() {
		this("");
	}

	/**
	 * params 格式如同
	 * &uploadcommand=needsave&tableinftablename=b2cgcodeimage&imagepath
	 * =imagepath&columns=bcode,&values=123, uploadcommand 命令名
	 * tableinftablename：存储的表名 imagepath 图片路径 columns：字段 用,分开 values ：值用 ,分开
	 * 可以传命令到服务器 @see BaseFileUploadServletFinal uploadcommand ：mankeflow
	 * updateprint 等具体参看服务器的类
	 * 
	 * @param params
	 */
	public SWFFileUpload(String params) {
		//this.params = params;
		init();
		uploadbutton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				showDialog();

			}

		});
		d.setHideOnButtonClick(true);
		d.setClosable(false);
	}

	/*
	 * public static SWFFileUpload getInstance() { if (swffileupload == null)
	 * swffileupload = new SWFFileUpload();
	 * 
	 * return swffileupload; }
	 */

	private void init() {

		d.setButtons(Dialog.OK);
		d.getButtonById(Dialog.OK).setText("关闭");
		d.setHeading("文件上传");
		d.setSize(444, 300);
		VerticalPanel hp = new VerticalPanel();
		hp.setSpacing(5);
		d.add(hp);
		
		// hp.setWidth("100%");

		builder
				.setFileTypes("*.*");
		builder.setFileTypesDescription("Attachment File");

		// Configure the button to display
		builder.setButtonPlaceholderID("swfupload");
		builder.setButtonImageURL("images/baseimage/swfupload.png");
		builder.setButtonWidth(180);
		builder.setButtonHeight(18);
		// builder.setButtonText("<span class=\"label\">请选择文件</span>");
		builder
				.setButtonText("<span class='button'>请选择文件 <span class='buttonSmall'>(最大 5 MB )</span></span>");

		builder
				.setButtonTextStyle(".button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }");
		// builder
		// .setButtonTextStyle(".label { color: #011000; font-family: sans font-size: 16pt;width=200px }");

		builder.setButtonTextLeftPadding(18);
		builder.setButtonTextTopPadding(0);
		builder.setFileQueueLimit(10);
		builder.setFileUploadLimit(20);
		builder.setFileSizeLimit(5120);
		builder.setDebug(false);

		// ---------------

		// ---------------
		builder.setUploadStartHandler(new UploadStartHandler() {

			@Override
			public void onUploadStart(UploadStartEvent e) {
				GWT.log("UploadStartHandler");

			}

		});
		builder.setUploadProgressHandler(new UploadProgressHandler() {

			@Override
			public void onUploadProgress(UploadProgressEvent e) {
				GWT
						.log("UploadProgressHandler complete="
								+ e.getBytesComplete() + " total ="
								+ e.getBytesTotal());
				File f = e.getFile();
				f.getName();
				// String text = html.getHTML();
				// text += "<br />" + e.getBytesComplete() + "; " + f.getName();
				// html.setHTML(text);

			}

		});
		builder.setUploadErrorHandler(new UploadErrorHandler() {

			@Override
			public void onUploadError(UploadErrorEvent e) {
				File ff = e.getFile();
				// String message = e.getMessage();
				// if (message == null || message.trim().length() == 0) {
				// message = "upload failed";
				// }
				// String t = html.getHTML();
				// t += "<br />error: " + ff.getId() + ", " + ff.getName() +
				// " / " + message;
				// html.setHTML(t);
				 String message = e.getMessage();
				 GWT.log( ff.getId() + ", " + ff.getName()+""+message);
				removeFile(ff.getId());
				if (files.size() > 0) {
					ff = files.get(0);
					String id = ff.getId();
					// String tt = html.getHTML();
					// tt += "<br />start: " + id;
					// html.setHTML(tt);
					upload.startUpload(id);
				}
			}

		});

		builder.setSWFUploadLoadedHandler(new SWFUploadLoadedHandler() {

			@Override
			public void onSWFUploadLoaded() {
				GWT.log("SWFUploadLoadedHandler");

			}

		});
		builder.setFileQueueErrorHandler(new FileQueueErrorHandler() {

			@Override
			public void onFileQueueError(FileQueueErrorEvent e) {
				GWT.log("FileQueueErrorHandler");

			}

		});

		builder.setFileQueuedHandler(new FileQueuedHandler() {

			@Override
			public void onFileQueued(FileQueuedEvent event) {

				 String t ="";
				 t += "<br />ofq: " + event.getFile().getId() + "; "
				 + event.getFile().getName();
				 GWT.log("t="+t);
				// html2.setHTML(t);
				files.add(event.getFile());
			}

		});
		builder.setFileDialogCompleteHandler(new FileDialogCompleteHandler() {

			@Override
			public void onFileDialogComplete(FileDialogCompleteEvent e) {
				html.setHTML("你选择了 = " + files.size() + "个文件");

			}

		});
		builder.setDialogStartHandler(new DialogStartHandler() {

			@Override
			public void onDialogStart() {
				// File ff = files.get(0);
				// String id = ff.getId();
				// String t = html.getHTML();
				// t += "<br />start: " + id;
				// html.setHTML(t);
				// upload.startUpload(id);

			}

		});
		// Use ButtonAction.SELECT_FILE to only allow selection of a single file
		builder.setButtonAction(ButtonAction.SELECT_FILES);

		// The placeholder to be replaced by the swfupload control
		// This could also be provided statically by your host HTML page
		Element placeHolder = DOM.createDiv();
		placeHolder.setId("swfupload");
		// RootPanel.get().getElement().appendChild(placeHolder);

		// The button to start the transfer

		Html h = new Html(
				"<div style=\"width: 180px; height: 18px; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;\"><span id='swfupload'></span> <div>");
		Button uploadButton = new Button("上传");

		HorizontalPanel hpanel = new HorizontalPanel();

		// hpanel.getElement().appendChild(placeHolder);
		hpanel.add(h);
		hpanel.add(uploadButton);

		hp.add(hpanel);
		hp.add(html);

		builder.setUploadCompleteHandler(new UploadCompleteHandler() {

			@Override
			public void onUploadComplete(UploadCompleteEvent e) {
				GWT.log("UploadCompleteHandler");
				File f = e.getFile();
				String t = html.getHTML();
				t += "<br />上传完成 : " + f.getId() + ", " + f.getName();
				html.setHTML(t);
				GWT.log("files.size()=" + files.size());
				GWT.log("files.size()=" + files);
				GWT.log("f.getid()=" + f.getId());
				
				removeFile(f.getId());
				if (files.size() > 0) {
					File ff = files.get(0);
					String id = ff.getId();
					// String tt = html.getHTML();
					// tt += "<br />start: " + id;
					// html.setHTML(tt);
					// GWT.log("id="+id);
					upload.startUpload(id);
				}

			}

		});

		builder.setUploadSuccessHandler(new UploadSuccessHandler() {

			@Override
			public void onUploadSuccess(UploadSuccessEvent e) {
				GWT.log("UploadSuccessHandler");
				// String t = html.getHTML();
				// t += "<br />server data : " + e.getServerData();
				// html.setHTML(t);
			}

		});

		uploadButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				// while(filecount>0)
				{
					upload.startUpload();
					// filecount--;
				}
			}

		});

	}

	private void removeFile(String id) {
		Iterator<File> ite  = files.iterator();
			while(ite.hasNext())
			{
				
				if(ite.next().getId().equals(id))
				{
					ite.remove();
				}
			}
/*		for (File ff : files) {
			GWT.log("id = "+ff.getId()+" name = "+ff.getName()+" index="+ff.getIndex());
//			if (ff.getId().toString().equals(id)) {
//				files.remove(ff);
//			}
//			
			String idd = ff.getId();
			GWT.log("idd="+idd);
			if (idd.equals(id)) {
				files.remove(ff);
			}
			
		}*/
//		if(files.size()>0)
//		files.remove(0);
		GWT.log("ss");
	}

	public void showDialog() {
		builder.setUploadURL("gwtbase/BaseFileUploadServletFinal?env_bcode="
				+ Env.getEnvbcode() + params);
		d.show(); 
		upload = builder.build();
	}

	public Button getUploadbutton() {
		return uploadbutton;
	}

	public void setUploadbutton(Button uploadbutton) {
		this.uploadbutton = uploadbutton;
	}

	public String getParams() {
		return params;
	}

	/**
	 * 设置上传参数 &uploadcommand=needsave&tableinftablename=bcode_extdata&imagepath=
	 * imagepath&columns=bcode,&values=123,
	 * 
	 * @param params
	 */
	public void setParams(String params) {
		this.params = params;
	}

}
